<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../Css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="../Css/bootstrap-responsive.css" />
    <link rel="stylesheet" type="text/css" href="../Css/style.css" />
    <script type="text/javascript" src="../Js/jquery.js"></script>
    <script type="text/javascript" src="../Js/bootstrap.js"></script>
    <script type="text/javascript" src="../Js/ckform.js"></script>
    <script type="text/javascript" src="../Js/common.js"></script>

    <style type="text/css">
        body {
            padding-bottom: 40px;
        }
        .sidebar-nav {
            padding: 9px 0;
        }

        @media (max-width: 980px) {
            /* Enable use of floated navbar text */
            .navbar-text.pull-right {
                float: none;
                padding-left: 5px;
                padding-right: 5px;
            }
        }
        .warning{
            border-color: red !important;
        }

    </style>
</head>
<body>
<form class="definewidth m20" >
<table class="table table-bordered table-hover definewidth m10">
    <tr>
        <td width="10%" class="tableleft">角色名称</td>
        <td><input type="text" onblur="roleNameCheck(this.value)" name="rName" value=""/></td>
    </tr>
    <tr>
        <td class="tableleft">状态</td>
        <td>
            <input type="radio" name="rState" value="0" checked /> 启用
           <input type="radio" name="rState" value="1"  /> 禁用
        </td>
    </tr>
    <tr>
        <td class="tableleft">权限</td>
        <td id="my-con">

		</td>
    </tr>
    <tr>
        <td class="tableleft"></td>
        <td>
<!--            onclick="updateRole()"-->
            <button id="role-update-btn" class="btn btn-primary"  type="button">更新</button> &nbsp;&nbsp;<button type="button" class="btn btn-success" name="backid" id="backid">返回列表</button>
        </td>
    </tr>
</table>
</form>
</body>
</html>
<script>
    let rId = document.location.toString().GetValue("rId");
    // 原角色名
    let oldRName;
    // 查询的用户信息
    let globleRole;
    // 发送添加标志,一旦发送即锁死,防止多次添加
    let sendUpdateFlag = true;
    // 设置定时器, 防止onblur和onclick发生冲突, 确保onclick先执行
    let roleNameCheckTime;
    // 角色名唯一,非空检测标志
    let roleNameCheckFlag = false;

    // 查询所有资源信息,遍历生成列表
    function queryMenuList(){
        layer.load(0)
        $.ajax({
            type: "GET",
            url: origin + "/menu/list",
            data: {pageSize:999,pageNum:1,jwtToken:jwtToken},
            dataType: "json",
            async: false,
			xhrFields: {
			   withCredentials: true
			},
			crossDomain: true,
            success: function (data) {
                layer.closeAll()
                if (data.code == 200){
                    $.each(data.obj.list, function () {
                        let _ul = "<ul><label class='checkbox inline'><input id='mid_"+ this.mId +"' type='checkbox' name='group[]' value='"+ this.mId +"' />"+ this.mName +"</label></ul>"
                        $("#my-con").append($(_ul));
                    })
                    // 延时等待查询出globleRole
                    delayForGlobleRole();
                }else{
                    layer.msg(data.msg,function(){})
                }
            },
            complete : function(xhr, status) {
                myComplete(xhr, status);
            }
        })
    }
    // 延时等待查询出globleRole
    function delayForGlobleRole(){
        setTimeout(function(){
            if(globleRole == undefined){
                delayForGlobleRole()
            }else{
                fillRoleDate(globleRole);
            }
        },20)
    }
    // 根据rId查询role信息
    function queryByRId(){
        layer.load(0)
        $.ajax({
            type: "GET",
            url: origin + "/role/" + rId,
            data: {jwtToken:jwtToken},
            dataType: "json",
			xhrFields: {
			   withCredentials: true
			},
			crossDomain: true,
            success: function (data) {
                layer.closeAll()
                if (data.code == 200){
                    // 填充role信息
                    globleRole = data.obj;
                }else{
                    layer.msg(data.msg,function(){})
                }
            },
            complete : function(xhr, status) {
                myComplete(xhr, status);
            }
        })
    }
    // 填充role信息
    function fillRoleDate(role){
        // 填充角色名
        $("input[name='rName']").val(role.rName);
        oldRName = role.rName;
        // 填充状态
        if(role.rState == 0){
            $("input[name='rState']").eq(1).prop("checked",false)
            $("input[name='rState']").eq(0).prop("checked",true)
        }else{
            $("input[name='rState']").eq(0).prop("checked",false)
            $("input[name='rState']").eq(1).prop("checked",true)
        }
        // 填充权限
        $.each(role.roleMenuList, function(){
            $("#mid_" + this.mId).prop("checked",true)
        })
    }
    // 角色名唯一,非空检测
    function roleNameCheck(rName){
        roleNameCheckTime = setTimeout(function(){
            if(rName == null || rName == "" || rName == undefined){
                layer.msg("角色名不能为空", function(){})
                $("input[name='rName']").addClass("warning")
            }else{
                if(rName.trim() == oldRName.trim()){
                    roleNameCheckFlag = true;
                    $("input[name='rName']").removeClass("warning")
                }else{
                    layer.load(0)
                    $.ajax({
                        type: "GET",
                        url: origin + "/role/r-name/" + rName,
                        data: {jwtToken:jwtToken},
                        dataType: "json",
                        async: false,
						xhrFields: {
						   withCredentials: true
						},
						crossDomain: true,
                        success: function (data) {
                            layer.closeAll()
                            if (data.code == 200){
                                roleNameCheckFlag = true;
                                $("input[name='rName']").removeClass("warning")
                            }else{
                                layer.msg("角色名已存在，请重新输入。", function(){})
                                roleNameCheckFlag = false;
                                $("input[name='rName']").addClass("warning")
                            }
                        }
                        // TODO: 后端拦截ajax请求进行登陆跳转需要前端相互配合, 每一个ajax请求都需要加上以下的代码
                        ,complete : function(xhr, status) {
                            myComplete(xhr, status);
                        }
                    })
                }
            }
        },120)
    }
    // 添加角色信息
    function updateRole(){
        // 防止onblur和onclick发生冲突, 确保onclick先执行
        clearTimeout(roleNameCheckTime)
        let rName = $("input[name='rName']").val().trim();
        let rState = $("input[name='rState']:checked").val().trim();
        var menuIds = "";
        $.each($("input[name='group[]']:checked"), function(){
            menuIds += $(this).val().trim() + "_"
        })
        // 角色名的唯一性验证, 非空
        roleNameCheck(rName);
        // 延时确保ajax已经发送
        setTimeout(function(){
            if( !roleNameCheckFlag ){
                return false;
            }
            // 验证没问题, 添加数据
            if(sendUpdateFlag){
                // 一旦提交即锁死, 防止多次请求
                sendUpdateFlag = false;
                layer.load(0)
                $.ajax({
                    type: "POST",
                    url: origin + "/role/" + rId,
                    data: {rName:rName,rState:rState,menuIds:menuIds,_method:"PUT",jwtToken:jwtToken},
                    dataType: "json",
					xhrFields: {
					   withCredentials: true
					},
					crossDomain: true,
                    success: function (data) {
                        layer.closeAll()
                        if (data.code == 200){
                            layer.msg("更新成功")
                            setTimeout(function(){
                                // 返回index
                                $('#backid').trigger("click");
                            },500)
                        }else{
                            layer.msg(data.msg,function(){})
                        }
                    },
                    complete : function(xhr, status) {
                        myComplete(xhr, status);
                    }
                })
            }
        },150)
    }

    $(function () {
        // 查询所有资源信息,遍历生成列表
        queryMenuList();
        // 查询角色数据
        queryByRId();
        $(':checkbox[name="group[]"]').click(function () {
            $(':checkbox', $(this).closest('li')).prop('checked', this.checked);
        });
        $('#backid').click(function(){
            window.location.href="index.html?pageNum=" + globalPageNum + "&pageSize=" + globalPageSize;
        });
        // 监听修改按钮
        $("#role-update-btn").on("click", function(){updateRole()})
    });
</script>